import '@/utils'
import Vue from 'vue'
import Ivzone from '@/components/ivzone'
import Global from "@/components/global.config"
import IvzBasicView from '@/components/view/IvzBasicView'
import {mapToUrl} from '@/utils/json.utils'
import VueClipboard from 'vue-clipboard2'
import moment from 'moment';

Vue.use(Ivzone);
Vue.use(VueClipboard)

const config = {
	table:{
		pagination: {
			defaultPageSize:20
			,defaultCurrent:1
			,total:10
			,current:1
			,pageSize:20
			,selfChange:(page, size)=>{
				config.table.pagination.current = page;
				vue.queryParams.size = size;
				vue.queryParams.index = page;
				vue.queryData();
			}
		},
	},
	search: {}
}

const typeData = [
	{label: '小图', value: 'SMALL'},
	{label: '多图', value: 'MANY'},
	{label: '大图', value: 'BIG'}
]

const formatter = function (text) {
	if(!text){
		return text
	}
	let tm = new Date(text)
	return moment(tm).format('YYYY-MM-DD HH:mm:ss')
}

const renderSize = function(filesize){
	if(null==filesize || filesize === ''){
		return "0 Bytes";
	}
	let unitArr = ["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"];
	let index=0;
	let srcsize = parseFloat(filesize);
	index=Math.floor(Math.log(srcsize)/Math.log(1024));
	let size =srcsize/Math.pow(1024,index);
	size=size.toFixed(2);//保留的小数位数
	return size+unitArr[index];
}

const column = [
	{field: 'name', title: '名称', type: 'text', width: 230},
	{field: 'mime', title: '类型', type: 'text'},
	{field: 'size', title: '文件大小', formatter: renderSize},
	{field: 'ipfs', title: '唯一ID'},
	// {field: 'type', title: '类型', type: 'radio', data: typeData},
	{field: 'ts', title: '创建时间', formatter},
	{field: 'action', title: '操作', type: 'action', width: 230}
]

const pressEnter = m=>{
	vue.queryParams.query=m;
	vue.queryParams.index=1;
	vue.queryData();
}

const searchMetas = [
	{field: 'query', title: '综合搜索', type: 'text', default: '', clear:true, event:{pressEnter}},
	{field: 'mime', title: '文件类型', type: 'text', default: '', clear:true},
	{field: 'cid', title: '唯一ID', type: 'text', default:'', clear:true},
	{field: 'createTime', title: '更新时间', type: 'dateRange', clear:true},
];

const vue = new Vue({
    el: '#index',
    components: {IvzBasicView},
    data:{
		colData:[],
		metas: column,
		config,
		searchMetas,
		visible: false,
		queryParams:{index:1, size:20,query:null,tags:null,sortList:{createTime:false}}
    },
    created () {
    	//设置标题
    	this.$page['menu']['name'] = "IPFS文件搜索系统";
    	//设置表行的按钮
        this.$page.addActionMeta("model", {
            id: 'model',
            position: 'T',
            label: '复试CID',
            callBack: (model) => {
				this.$copyText(`${model.ipfs}`)
					.then(res=>{
						this.$message.success("复制成功");
				});
                return new Promise((resolve, reject) => {
                });
            }
        });
		this.$page.addActionMeta("default", {
			id: 'Default',
			position: 'T',
			label: '复制URL',
			callBack: (model) => {
				this.$copyText(`${Global.ipfsApi}/cat/${model.ipfs}`)
					.then(res=>{
						this.$message.success("复制成功");
					});
				return new Promise((resolve, reject) => {
				});
			}
		});
		this.$page.addActionMeta("view", {
			id: 'View',
			position: 'T',
			sort: 101,
			label: '下载',
			callBack: (model) => {
				window.open(`${Global.ipfsApi}/cat/${model.ipfs}`);
				return new Promise((resolve, reject) => {
				});
			}
		});
		//设置右上角按钮
		this.$page.addActionMeta("Search", {
			id: "search",label:"搜索", type:'primary',position: 'M',callBack:(mm)=>{
				this.queryParams.index = 1;
				this.queryParams.query = mm.query || null;
				this.queryParams.mime = mm.mime || null;
				this.queryParams.cid = mm.cid || null;
				if(mm.createTime && mm.createTime.length === 2){
					this.queryParams['minTime'] = mm.createTime[0].utcOffset(480).format('YYYY-MM-DD HH:mm:ss');
					this.queryParams['maxTime'] = mm.createTime[1].utcOffset(480).format('YYYY-MM-DD HH:mm:ss');
				}else{
					this.queryParams['minTime'] = null;
					this.queryParams['maxTime'] = null;
				}
				return this.queryData();
			}
		});
		this.queryData();
    },
    methods: {
        jump(params){
        	params = params || {};
            this.$nav({path: '/pages/markdown.html?'+mapToUrl({id:params.id, tp:'article'}), params:{}, refresh: true});
        },
		queryData(obj){
			obj = obj || this.queryParams;
			return this.$http.post(Global.ipfsApi+ '/ipfs/search',obj).then(res=>{
				if(res.ok){
					this.colData = res.data;
					this.config.table.pagination.total = res.total;
					this.config.table.pagination.current = this.queryParams.index;
					this.config.table.pagination.pageSize = this.queryParams.size;
				}
			}).catch(err=>{
				console.log(err);
			});
		}
    }
})
